const socketio = require('socket.io');
const logger = require('./logger');

/**
 * socketio
 */
let io;

module.exports.connect = (server) => {
  io = socketio(server, {
    transports: ['websocket', 'polling']
  });

  io.on('connection', async (socket) => {
    const { id } = socket;

    const { query } = socket.handshake;

    logger.log('id - connected', id);
    logger.log('with query', JSON.stringify(query));

    socket.emit('res', 'connected!');

    socket.on('disconnect', async (reason) => {
      logger.log(`socket.id: ${socket.id} disconnected. reason: ${reason}`);
    });
  });
};

module.exports.getSocketIO = () => io;

/**
 * 给socket.io client发送事件及数据
 * @param {*} event 事件名称
 * @param {*} data 数据
 */
module.exports.sendEventToAllClient = async (event, data) => {
  if (io) {
    const sockets = await io.fetchSockets();
    console.log('sockets.length', sockets.length);
    for (const socket of sockets) {
      socket.emit(event, data, (response) => {
        logger.log('response from socket.io client', response); // "got it"
      });
    }
  }
};
